<?php

class DatabaseResult
{
	public static $currentQuery;
	/** @var int */
	public $time;
	/** @var PDOStatement */
	public $statement;
	/** @var string */
	public $lastInsertId;
	/** @var ADatabase */
	public $database;
	/** @var string */
	public $query;
	/** @var boolean */
	public $success;
	/** @var int */
	public $resultRows;
	/** @var int */
	public $foundRows;
	
	public function displaySimpleTable()
	{
		$i = 0;
		echo '<table class="resultTable">';
		while($row = $this->statement->fetch(\PDO::FETCH_ASSOC))
		{
			if($i == 0)
			{
				echo '<thead>';
					echo '<tr>';
						foreach($row as $colName => $colValue)
						{
							echo '<th>'.H($colName).'</th>';
						}
					echo '</tr>';
				echo '</thead>';
				echo '<tbody>';
			}
			echo '<tr>';
				foreach($row as $colName => $colValue)
				{
					echo '<td>'.H($colValue).'</td>';
				}
			echo '</tr>';
			$i++;
			if($i == $this->statement->rowCount())
			{
				echo '</tbody>';
			}
		}
		echo '</table>';
	}
	
	/**
	 * Display the result sets and query information in the main panel
	 */
	public function displayResult()
	{
		$this->displayQueryDetails();
		$this->displayQueryResults();
	}
	
	public function displayQueryDetails()
	{
		self::$currentQuery = $this->query;
		echo '<div class="executedQuery">';
			echo '<b>Executed Query</b><br>';
			echo '<pre class="queryString">';
				echo $this->query;
			echo '</pre>';
			echo '<table>';
				echo '<tr>';
					echo '<th>Query Time</th>';
					echo '<td>'.\number_format($this->time, 3).'</td>';
				echo '</tr>';
				echo '<tr>';
					echo '<th>Success</th>';
					echo '<td>'.($this->success?'Yes':'No').'</td>';
				echo '</tr>';
				if(!$this->success)
				{
					$errorInfo = $this->statement->errorInfo();
					echo '<tr>';
						echo '<th>Error</th>';
						echo '<td>'.H($errorInfo[2]).'</td>';
					echo '</tr>';
				}
				if(isset($this->resultRows))
				{
					echo '<tr>';
						echo '<th>Rows</th>';
						echo '<td>'.H($this->resultRows).'</td>';
					echo '</tr>';
				}
				if(isset($this->foundRows))
				{
					echo '<tr>';
						echo '<th>Total Rows</th>';
						echo '<td>'.H($this->foundRows).'</td>';
					echo '</tr>';
				}
			echo '</table>';
		echo '</div>';
	}
	public function displayQueryResults()
	{
		echo '<div class="queryResults">';
			do
			{
				if($this->statement->rowCount() == 0)
				{
					echo '<div class="neutral message">';
						echo 'No results';
					echo '</div>';
				}
				else
				{
					$this->displaySimpleTable();
				}
			} while($this->statement->nextRowset());
		echo '</div>';
	}
}